﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;

//adding libraries for handling word documents.
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Runtime.InteropServices;


namespace WordDocEditTest {
    public partial class Form1 : Form {
        //create a new Random class, for use when generating temp file names
        Random rand = new Random();

        object o = Missing.Value;
        object oFalse = false;
        object oTrue = true;

        Word._Application app = null;
        Word.Documents docs = null;
        Word.Document doc = null;

        string path = @"C:\Users\jye\Google Drive\Documents\University\status.doc";

        public Form1() {
            InitializeComponent();
            Dictionary<string, string> replace = new Dictionary<string, string>();
            replace.Add("<[[CITY]]>", "Canberra");
            replace.Add("<[[NAME]]>", "Jye Cusch");
            replace.Add("<[[NUMBER]]>", "16");

            generateAgreement(path, replace);
        }

        public void generateAgreement(string templatePath, Dictionary<string, string> replacements) {
            //set document path
            object path = createTempFile(templatePath);
            try {
                //Open Microsoft Word
                app = new Word.Application();
                app.Visible = false;
                app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
                //Open the document
                docs = app.Documents;
                doc = docs.Open(ref path, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
                doc.Activate();

                //Replace each key, with it's associated value
                foreach (KeyValuePair<string, string> replacement in replacements) {
                    foreach (Word.Range range in doc.StoryRanges) {
                        Word.Find find = range.Find;
                        //set text to find and text to replace it with
                        //  e.g. Key = <[[CITY]]> and Value = "Canberra"
                        object findText = replacement.Key;
                        object replacText = replacement.Value;
                        object replace = Word.WdReplace.wdReplaceAll;
                        object findWrap = Word.WdFindWrap.wdFindContinue;

                        find.Execute(ref findText, ref o, ref o, ref o, ref oFalse, ref o,
                            ref o, ref findWrap, ref o, ref replacText,
                            ref replace, ref o, ref o, ref o, ref o);

                        Marshal.FinalReleaseComObject(find);
                        Marshal.FinalReleaseComObject(range);
                    }
                }

                doc.Save();
                //The temporary document has been generated and saved, show it in Word.
                app.Visible = true;
                //((Word._Document)doc).Close(ref o, ref o, ref o);
                //app.Quit(ref o, ref o, ref o);
            } finally {
                if (doc != null)
                    Marshal.FinalReleaseComObject(doc);

                if (docs != null)
                    Marshal.FinalReleaseComObject(docs);

                if (app != null)
                    Marshal.FinalReleaseComObject(app);
            }
        }

        public string createTempFile(string pathToOriginal) {
            //create a temporary file name
            string tmpFileName = "tmp" + rand.Next().ToString() + Path.GetFileName(pathToOriginal);
            //get the path to the temporary folder
            string tmpFileLocation = Path.GetTempPath();
            //create the full path to the tmp file
            string tmpFullPath = Path.Combine(tmpFileLocation, tmpFileName);
            
            //copy the original file to the new tmp path
            File.Copy(pathToOriginal, tmpFullPath);

            //return the tmp file's path
            return tmpFullPath;
        }
    }
}
